<template>
  <div class="app-container">
    <!-- 条件查询区域开始 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-row>
          <el-col :span="6">
            <el-form-item :label="$t('sysUser.directory')" prop="directoryId">
              <el-select
                v-model="queryParams.directoryId"
                :placeholder="$t('sysUser.directoryRequired')"
                clearable
                class="!w-[203px]"
              >
                <el-option
                  v-for="item in directoryList"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('sysUser.username')" prop="loginName">
              <el-input
                v-model="queryParams.loginName"
                :placeholder="$t('sysUser.usernameRequired')"
                class="!w-[203px]"
                clearable
                @keyup.enter="tableHooks.handleQuery()"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('sysUser.fullName')" prop="realName">
              <el-input
                v-model="queryParams.realName"
                :placeholder="$t('sysUser.fullNameRequired')"
                class="!w-[203px]"
                clearable
                @keyup.enter="tableHooks.handleQuery()"
              />
            </el-form-item> </el-col
          ><el-col :span="6">
            <el-form-item :label="$t('sysUser.nickname')" prop="likeNickName">
              <el-input
                v-model="queryParams.likeNickName"
                :placeholder="$t('sysUser.nicknameRequired')"
                class="!w-[203px]"
                clearable
                @keyup.enter="tableHooks.handleQuery()"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item :label="$t('sysUser.department')" prop="deptId">
              <el-tree-select
                v-model="queryParams.deptId"
                :data="deptList"
                :render-after-expand="false"
                filterable
                class="!w-[203px]"
                check-strictly
                :placeholder="$t('sysUser.departmentRequired')"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('sysUser.state')" prop="userStatus">
              <jmash-enum-select
                v-model="queryParams.userStatus"
                :placeholder="$t('sysUser.stateRequired')"
                enum-type="jmash.rbac.protobuf.UserStatus"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('sysUser.isDeleted')" prop="showDeleted">
              <el-select
                v-model="queryParams.showDeleted"
                :placeholder="$t('sysUser.isDeletedRequired')"
                clearable
                class="!w-[203px]"
              >
                <el-option :label="$t('sysUser.show')" :value="true" />
                <el-option :label="$t('sysUser.hide')" :value="false" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item class="search-btn">
              <el-button type="primary" @click="tableHooks.handleQuery()">
                {{ $t("common.search") }}
              </el-button>
              <el-button @click="tableHooks.resetQuery()">{{
                $t("common.reset")
              }}</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="clear"></div>
    </div>
    <!-- 条件查询区域结束 -->
    <el-card shadow="never" class="table-container">
      <!-- 按钮开始 -->
      <template #header>
        <el-row justify="space-between">
          <el-col :span="17">
            <el-button
              v-hasPerm="['rbac:user:add']"
              type="primary"
              @click="handleAdd"
            >
              {{ $t("common.add") }}
            </el-button>
            <el-button
              v-if="$route.query.tenant?.includes('@')"
              v-hasPerm="['rbac:user:add']"
              type="primary"
              @click="handlePlatformAdd"
            >
              {{ $t("sysUser.PlatformAdd") }}
            </el-button>
            <el-button
              v-hasPerm="['rbac:user:delete']"
              type="primary"
              @click="tableHooks.deleteRecords()"
            >
              {{ $t("common.batchDelete") }}
            </el-button>
            <el-dropdown
              v-hasPerm="['rbac:user:enable']"
              class="dropdown-left"
              @command="enableRecords"
            >
              <el-button type="primary">
                {{ $t("common.enable") }}/{{ $t("common.disable") }}
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="true">
                    <el-icon size="14">
                      <Unlock />
                    </el-icon>
                    {{ $t("common.enable") }}
                  </el-dropdown-item>
                  <el-dropdown-item command="false">
                    <el-icon size="14">
                      <Lock />
                    </el-icon>
                    {{ $t("common.disable") }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
          <el-col :span="7" class="container-float">
            <el-button
              v-hasPerm="['rbac:user:import']"
              plain
              type="primary"
              @click="uploadVisible = true"
            >
              {{ $t("common.import") }}
            </el-button>
            <el-button
              v-hasPerm="['rbac:user:export']"
              plain
              type="primary"
              @click="tableHooks.handleExport(t('sysUser.name'))"
            >
              {{ $t("common.export") }}
            </el-button>
            <el-button
              v-hasPerm="['rbac:user:print']"
              plain
              type="primary"
              @click="tableHooks.handleExportPdf(t('sysUser.name'))"
            >
              {{ $t("common.print") }}
            </el-button>
            <jmash-column-select
              v-model="tableLabel"
              label-name="rbac/rbac-user"
            />
          </el-col>
        </el-row>
      </template>
      <!-- 按钮结束 -->
      <!-- 表格开始 -->
      <jmash-table
        ref="multipleTableRef"
        row-key="userId"
        :list-loading="listLoading"
        :data="tableData"
        :table-label="tableLabel"
        @selection-change="tableSelected"
        @sort-change="handleSort"
      >
        <!-- 用户名 -->
        <template #userName="scope">
          <span>
            {{ scope.data.row.loginName }}
            <el-tag
              v-if="scope.data.row.approved === true"
              type="success"
              size="small"
            >
              {{ $t("sysUser.reviewed") }}
            </el-tag>
            <el-tag
              v-if="scope.data.row.approved === false"
              type="danger"
              size="small"
            >
              {{ $t("sysUser.notReviewed") }}
            </el-tag>
          </span>
        </template>
        <!-- 性别 -->
        <template #sexType="scope">
          <span>
            {{ Dict.genderEnum.getEnumValue(scope.data.row.gender) }}
          </span>
        </template>
        <template #mobileIns="scope">
          <span v-if="!scope.data.row.mobileEncrypt">
            {{ scope.data.row.mobilePhoneIns }}
          </span>
          <span v-else>
            {{ scope.data.row.mobilePhone }}
          </span>
          <span v-if="scope.data.row.mobilePhoneIns">
            <el-tag
              v-if="scope.data.row.phoneApproved === true"
              size="small"
              type="success"
            >
              {{ $t("sysUser.reviewed") }}
            </el-tag>
            <el-tag
              v-if="scope.data.row.phoneApproved === false"
              size="small"
              type="danger"
            >
              {{ $t("sysUser.notReviewed") }}
            </el-tag>
          </span>
          <span v-if="scope.data.row.mobilePhoneIns" class="distance-left">
            <svg-icon
              v-show="!scope.data.row.mobileEncrypt"
              icon-class="close-eye"
              @click="mobileEncryptEvent(scope.data.row)"
            />
            <svg-icon
              v-show="scope.data.row.mobileEncrypt"
              icon-class="eye-open"
              @click="mobileEncryptEvent(scope.data.row)"
            />
          </span>
        </template>
        <!-- 邮箱 -->
        <template #email="scope">
          <span>
            {{ scope.data.row.email }}
          </span>
          <span v-if="scope.data.row.email">
            <el-tag
              v-if="scope.data.row.emailApproved === true"
              type="success"
              size="small"
            >
              {{ $t("sysUser.reviewed") }}
            </el-tag>
            <el-tag
              v-if="scope.data.row.emailApproved === false"
              type="danger"
              size="small"
            >
              {{ $t("sysUser.notReviewed") }}
            </el-tag>
          </span>
        </template>
        <template #audit="scope">
          <el-switch
            v-model="scope.data.row.approved"
            @change="handleAudit(scope.data.row, scope.data.row.approved)"
          />
        </template>
        <template #status="scope">
          <el-tag v-if="scope.data.row.status === 'locked'" type="danger">
            {{ $t("common.lock") }}
          </el-tag>
          <span v-else>
            <el-switch
              v-model="scope.data.row.status"
              active-value="enabled"
              inactive-value="disabled"
              @click="
                tableHooks.enableRecord(
                  scope.data.row,
                  scope.data.row.status === 'enabled',
                )
              "
            />
          </span>
        </template>
        <template #operation="scope">
          <span
            v-hasPerm="['rbac:user:update']"
            class="el-button-color"
            @click="handleEdit(scope.data.row)"
          >
            {{ $t("common.edit") }}
          </span>
          <span
            v-hasPerm="['rbac:user:delete']"
            class="el-button-color dropdown-left"
            @click="tableHooks.deleteRecord(scope.data.row)"
          >
            {{ $t("common.delete") }}
          </span>
          <el-dropdown class="dropdown-left">
            <span class="el-dropdown-link">
              {{ $t("common.more") }}
              <el-icon class="el-icon--right">
                <arrow-down />
              </el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <div v-hasPerm="['rbac:user:reset']">
                  <el-dropdown-item @click="handleResetPwd(scope.data.row)">
                    {{ $t("common.resetPwd") }}
                  </el-dropdown-item>
                </div>
                <div v-hasRole="['tester']">
                  <el-dropdown-item @click="handleChangeUser(scope.data.row)">
                    {{ $t("common.switch") }}
                  </el-dropdown-item>
                </div>
                <div v-hasPerm="['rbac:user:unlock']">
                  <el-dropdown-item @click="handleUnlock(scope.data.row)">
                    {{ $t("sysUser.unlock") }}
                  </el-dropdown-item>
                </div>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </jmash-table>
      <template #footer>
        <jmash-pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:current-page="queryParams.curPage"
          v-model:page-size="queryParams.pageSize"
          @pagination="tableHooks.getList()"
        />
        &nbsp;
      </template>
    </el-card>
    <user-edit
      v-if="dialog.visible"
      v-model="dialog.visible"
      :title="dialog.title"
      width="900px"
      :entity-key="entityKey"
      @refresh="refresh"
    />
    <import-upload
      v-if="uploadVisible"
      :upload-visible="uploadVisible"
      :template-title="$t('sysUser.templateDownload')"
      @template-down="tableHooks.downloadTemplate(t('sysUser.name'))"
      @import-events="importExcel"
      @upload-closed="uploadClosed"
    />
    <!-- 重置密码 -->
    <reset-pwd
      v-if="pwdVisible"
      v-model="pwdVisible"
      :entity-key="entityKey"
      :title="$t('common.resetPwd')"
      width="550px"
      @refresh="refresh"
    />
    <platform-add
      v-if="addDialog.visible"
      v-model="addDialog.visible"
      :title="addDialog.title"
      width="400px"
      @refresh="refresh"
    />
  </div>
</template>
<script setup lang="ts">
import { type Ref, ref, reactive, onBeforeMount } from "vue";
import {
  type TableColumn,
  type TableSort,
  type DialogRef,
  type LayEntry,
  useTableHooks,
  useUserStore,
  runAsUser,
} from "jmash-core";

import { useI18n } from "vue-i18n";
const { t } = useI18n();
import { ElMessage } from "element-plus";

import type {
  UserReq,
  UserKey,
  UserModel,
  UserImportReq,
  UserApprovedReq,
  UserLockReq,
} from "@/api/system/user/types";
import { Dict } from "@/api/system/index";

import { userApi } from "@/api/system/user/index";
import { deptApi } from "@/api/system/dept/index";

import userEdit from "./edit.vue";
import { ElMessageBox } from "element-plus";
import platformAdd from "./platform-add.vue";
const deptList = ref<LayEntry[]>(); // 部门列表
const directoryList = ref();
const queryParams = ref<UserReq>({
  curPage: 1,
  pageSize: 10,
  showDeleted: false,
});

console.log(Dict.genderEnum.values);

const {
  tableHooks,
  multipleTableRef,
  queryFormRef,
  listLoading,
  tableData,
  total,
} = useTableHooks(t, userApi, queryParams);

const tableLabel: Ref<TableColumn[]> = ref([
  {
    label: "sysUser.directory",
    prop: "directoryId",
    width: "100",
    sortable: true,
    isColumn: true,
  },
  {
    label: "sysUser.username",
    prop: "loginName",
    width: "180",
    slotName: "userName",
    columnType: "slot",
    sortable: true,
    isColumn: true,
  },
  {
    label: "sysUser.nickname",
    prop: "nickName",
    width: "100",
    isColumn: true,
    sortable: true,
  },
  {
    label: "sysUser.fullName",
    prop: "realName",
    width: "100",
    isColumn: true,
    sortable: true,
  },
  {
    label: "sysUser.gender",
    prop: "gender",
    width: "80",
    slotName: "sexType",
    columnType: "slot",
    isColumn: true,
    sortable: true,
  },
  {
    label: "sysUser.birthday",
    prop: "birthDate",
    width: "120",
    isColumn: true,
    sortable: true,
  },
  {
    label: "sysUser.phoneNumber",
    prop: "mobilePhoneIns",
    width: "190",
    slotName: "mobileIns",
    columnType: "slot",
    isColumn: true,
    sortable: true,
  },
  {
    label: "sysUser.email",
    prop: "email",
    width: "180",
    slotName: "email",
    columnType: "slot",
    isColumn: true,
    sortable: true,
  },
  {
    label: "sysUser.userAuditStatus",
    prop: "approved",
    width: "160",
    slotName: "audit",
    columnType: "slot",
    isColumn: true,
  },
  {
    label: "sysUser.state",
    prop: "status",
    width: "100",
    slotName: "status",
    columnType: "slot",
    isColumn: true,
  },
  {
    label: "common.operate",
    width: "200",
    slotName: "operation",
    columnType: "slot",
    fixed: "right",
    isColumn: true,
  },
]);
const dialog: DialogRef = reactive({
  title: "",
  visible: false,
});
// 新增平台用户
const addDialog: DialogRef = reactive({
  title: "",
  visible: false,
});
const uploadVisible = ref(false);
// 重置密码
let entityKey = reactive<UserKey>({});
let pwdVisible = ref(false);

// 切换用户身份
function handleChangeUser(row: UserModel) {
  ElMessageBox.confirm("确认切换该用户？", "提示", {
    cancelButtonText: t("common.cancel"),
    confirmButtonText: t("common.confirm"),
    type: "warning",
  })
    .then(() => {
      runAsUser(row.userId as string).then(async (response) => {
        if (response.status === 200) {
          useUserStore().user.roleCodes = [];
          useUserStore().user.permCodes = [];
          location.reload();
          ElMessage({
            message: "切换成功",
            type: "success",
          });
        }
      });
    })
    .catch(() => {});
}

// 手机号隐藏/显示
function mobileEncryptEvent(row: UserModel) {
  row.mobileEncrypt = !row.mobileEncrypt;
}

// 新增
function handleAdd() {
  entityKey = reactive<UserKey>({});
  dialog.visible = true;
  dialog.title = t("common.add");
}

// 新增平台用户
function handlePlatformAdd() {
  addDialog.title = t("sysUser.PlatformAdd");
  addDialog.visible = true;
}

// 编辑
function handleEdit(row: UserModel) {
  entityKey.userId = row.userId;
  dialog.title = t("common.edit");
  dialog.visible = true;
}

// 列表选中
function tableSelected(value: UserModel[]) {
  tableHooks.selectionRows.value = value;
}

// 重置密码
function handleResetPwd(row: UserModel) {
  pwdVisible.value = true;
  entityKey.userId = row.userId;
}

// 用户审核
function handleAudit(row: UserModel, value: string) {
  const temData = {
    tenant: useUserStore().user.tenant,
    approved: value,
    userId: [row.userId],
  } as UserApprovedReq;
  userApi.approveUserApi(temData).then(() => {});
}

/**
 * 从子组件传过来的事件，刷新列表
 *
 * @returns {void}
 */
function refresh(value: boolean) {
  if (value) {
    tableHooks.getList();
    treelistDept();
    getDirectoryApi();
  }
}

function enableRecords(command: string) {
  if (command === "false") {
    if (tableHooks.selectionRows.value.length === 0) {
      ElMessage({
        message: t("common.chooseDisable"),
        type: "warning",
      });
      return;
    }
    ElMessageBox.confirm(t("common.confirmDisable"), t("common.disable"), {
      cancelButtonText: t("common.cancel"),
      confirmButtonText: t("common.confirm"),
      type: "warning",
    })
      .then(() => {
        handleEnable(
          command,
          tableHooks.selectionRows.value.map(
            (item: UserKey) => item.userId as string,
          ),
        );
      })
      .catch(() => {});
  } else {
    if (tableHooks.selectionRows.value.length === 0) {
      ElMessage({
        message: t("common.chooseEnable"),
        type: "warning",
      });
      return;
    }
    ElMessageBox.confirm(t("common.confirmEnable"), t("common.enable"), {
      cancelButtonText: t("common.cancel"),
      confirmButtonText: t("common.confirm"),
      type: "warning",
    })
      .then(() => {
        handleEnable(
          command,
          tableHooks.selectionRows.value.map(
            (item: UserKey) => item.userId as string,
          ),
        );
      })
      .catch(() => {});
  }
}

// 启用禁用接口
function handleEnable(command: string, ids: string[]) {
  userApi.batchEnable({ userId: ids }, JSON.parse(command)).then((response) => {
    if (response.status === 200) {
      if (command === "true") {
        ElMessage({
          message:
            t("common.successEnable") + response.data + t("common.stripData"),
          type: "success",
        });
      } else {
        ElMessage({
          message:
            t("common.successDisable") + response.data + t("common.stripData"),
          type: "success",
        });
      }
      tableHooks.getList();
      multipleTableRef.value?.clearSelection();
    }
  });
}

// 解锁
function handleUnlock(row: UserModel) {
  ElMessageBox.confirm("确认解锁该用户？", "提示", {
    cancelButtonText: t("common.cancel"),
    confirmButtonText: t("common.confirm"),
    type: "warning",
  })
    .then(() => {
      const tempData = {
        tenant: useUserStore().user.tenant,
        lock: false,
        userId: [row.userId],
      } as UserLockReq;
      userApi.userUnlock(tempData).then((response) => {
        if (response.status === 200) {
          ElMessage({
            message: "解锁成功",
            type: "success",
          });
          tableHooks.getList();
        }
      });
    })
    .catch(() => {});
}

// 导入Excel.
function importExcel(val: UserImportReq) {
  val.updateMask = "";
  tableHooks.importExcel(val).then(() => {
    uploadVisible.value = false;
  });
}

// 关闭导入弹框
function uploadClosed() {
  uploadVisible.value = false;
}

// 处理排序
function handleSort(sort: TableSort) {
  tableHooks.handleSort(sort.prop, sort.order);
}

function treelistDept() {
  deptApi.treelistDept().then(({ data }) => {
    deptList.value = data.results;
  });
}
function getDirectoryApi() {
  userApi.getDirectoryApi().then(({ data }) => {
    directoryList.value = data.directoryId;
  });
}

// 获取缓存里的数据
tableHooks.getList();
onBeforeMount(() => {
  treelistDept();
  getDirectoryApi();
});
</script>
